<script setup lang="ts">
import {OrganizationApi} from '@/api/pb/organization'

interface TreeNode {
  value: number
  label: string
  parentId: number
  children: TreeNode[]
}

const value = defineModel<number>()

const list = ref<TreeNode[]>([])

const getList = async () => {
  clear()
  const res = (await OrganizationApi.getOrganizationList())
    .map((item) => {
      return {
        value: item.id,
        label: item.name,
        parentId: item.parentId,
        children: []
      } as TreeNode
    })

  const data: TreeNode[] = []
  res.forEach((item) => {
    data.push(item)

    const parentId = item.parentId
    if (parentId) {
      const parent = data.find((item) => item.value === parentId)
      parent?.children.push(item)
    }
  })

  res.forEach((item) => {
    if(!item.parentId) {
      list.value.push(item)
    }
  })
}

const clear = () => {
  list.value = []
}
defineExpose({ getList, clear })

onMounted(async () => {
  if (list.value.length === 0) {
    await getList()
  }
})

</script>

<template>
  <el-tree-select
    v-model="value"
    :data="list"
    placeholder="请选择组织"
  />
</template>

<style scoped lang="scss">

</style>
